﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using QuanLyShopThoiTrang.QuanLyShopThoiTrang_BUS_WS;
using COMExcel = Microsoft.Office.Interop.Excel;
using System.Data.OleDb;
namespace QuanLyShopThoiTrang
{
    public partial class NhapHang : Form
    {
        int iIndex = -1;
        QLSTT_BUSSoapClient ws = new QLSTT_BUSSoapClient();
        public NhapHang()
        {
            InitializeComponent();
        }

        private void NhapHang_Load(object sender, EventArgs e)
        {
            List<LoaiSanPham> listLoaiSP = ws.LoaiSanPham_LayDanhSach();
            /*foreach(LoaiSanPham lsp in listLoaiSP)
            {
                comboBox1.Items.Add(lsp.LoaiSanPham_Ten);
                comboBox1.Items[0].Tag = lsp;
            }*/
            comboBox2.DataSource = listLoaiSP;
            comboBox2.DisplayMember = "LoaiSanPham_Ten";

            NhaCungCap temp = new NhaCungCap();
            temp.MaNhaCungCap = -1;
            List<NhaCungCap> listNCC = ws.NhaCungCap_TraCuu(temp);

            comboBox1.DataSource = listNCC;
            comboBox1.DisplayMember = "NhaCungCap_Ten";
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
                textBox9.Enabled = true;
            else
                textBox9.Enabled = false;
        }


        private bool CheckGrid(SanPham sp)
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                SanPham s = (SanPham)row.Tag;
                if (s.SanPham_MaHang == sp.SanPham_MaHang)
                    return false;
            }
            return true;
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if(textBox1.Text == "" || textBox5.Text == "")
            {
                MessageBox.Show("Không được để trống mã hàng và tên hàng");
                return;
            }

            if(textBox4.Text == "" || textBox8.Text == "")
            {
                MessageBox.Show("Không được để trống giá mua và giá bán");
                return;
            }

            if(textBox6.Text == "")
            {
                MessageBox.Show("Không được để trống số lượng");
                return;
            }

            SanPham sp = new SanPham();
            sp.SanPham_MaHang = textBox1.Text;

            if(!CheckGrid(sp))
            {
                MessageBox.Show("Sản phẩm có mã hàng này đã có trong danh sách.");
                return;
            }
            sp.SanPham_Ten = textBox5.Text;

            LoaiSanPham lsp = (LoaiSanPham)comboBox2.SelectedItem;
            sp.MaLoaiSanPham = lsp.MaLoaiSanPham;

            NhaCungCap ncc = (NhaCungCap)comboBox1.SelectedItem;
            sp.MaNhaCungCap = ncc.MaNhaCungCap;

            sp.SanPham_NhanHieu = textBox3.Text;
            sp.SanPham_XuatXu = textBox7.Text;
            if (ws.KiemTraDouble(textBox4.Text))
                sp.SanPham_GiaKhiMua = double.Parse(textBox4.Text);
            else
            {
                MessageBox.Show("Giá mua không hợp lệ");
                return;
            }
            if (ws.KiemTraDouble(textBox8.Text))
                sp.SanPham_GiaKhiBan = double.Parse(textBox8.Text);
            else
            {
                MessageBox.Show("Giá bán không hợp lệ");
                return;
            }

            if (checkBox1.Checked)
            {
                if (ws.KiemTraDouble(textBox9.Text))
                    sp.SanPham_GiaUuDai = double.Parse(textBox9.Text);
                else
                {
                    MessageBox.Show("Giá ưu đãi không hợp lệ");
                    return;
                }
            }

            sp.SanPham_KichCo = textBox2.Text;
            if (ws.KiemTraInt(textBox6.Text))
                sp.SanPham_SoLuong = int.Parse(textBox6.Text);
            else
            {
                MessageBox.Show("Số lượng không hợp lệ");
                return;
            }
            sp.SanPham_HinhAnh = textBox10.Text;


            dataGridView1.Rows.Add(dataGridView1.Rows.Count + 1, sp.SanPham_MaHang, sp.SanPham_Ten, comboBox2.Text, comboBox1.Text, sp.SanPham_NhanHieu, sp.SanPham_XuatXu, sp.SanPham_KichCo, sp.SanPham_SoLuong, sp.SanPham_GiaKhiMua, sp.SanPham_GiaKhiBan, sp.SanPham_GiaUuDai, sp.SanPham_HinhAnh);
            dataGridView1.Rows[dataGridView1.Rows.Count - 1].Tag = sp;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();
            textBox5.Clear();
            textBox7.Clear();
            textBox8.Clear();
            textBox9.Clear();
            textBox10.Clear();
            textBox1.Focus();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "JPG Files|*.jpg";
            open.Title = "Chọn hình ảnh cho sản phẩm";
            open.InitialDirectory = Environment.CurrentDirectory;
            if (open.ShowDialog() == DialogResult.OK)
            {
                textBox10.Text = open.FileName;
            }
        }

        private void button7_Click(object sender, EventArgs e)
        {
            textBox10.Text = "";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            foreach(DataGridViewCell cell in dataGridView1.SelectedCells)
            {
                dataGridView1.Rows.RemoveAt(cell.RowIndex);
            }

            foreach(DataGridViewRow row in dataGridView1.Rows)
            {
                row.SetValues(row.Index + 1);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            List<SanPham> listSP = new List<SanPham>();
            foreach(DataGridViewRow row in dataGridView1.Rows)
            {
                SanPham sp = (SanPham)row.Tag;
                sp.SanPham_TrangThai = "Su dung";
                listSP.Add(sp);
            }

            //List<SanPham> returnList = ws.SanPham_Them(listSP);
            bool kq = ws.SanPham_Them(new SanPhamDTO());

            if (kq)
            {
                MessageBox.Show("Một số sản phẩm đã thêm không thành công, đã được giữ lại trong list. Hãy kiểm ra lại.");
                dataGridView1.Rows.Clear();
                //foreach (SanPham sp in returnList)
                //{
                //    LoaiSanPham lsp = ws.SanPham_LayLoaiSP(sp);
                //    NhaCungCap ncc = ws.SanPham_LayNCC(sp);
                //    dataGridView1.Rows.Add(dataGridView1.Rows.Count + 1, sp.SanPham_MaHang, sp.SanPham_Ten, lsp.LoaiSanPham_Ten, ncc.NhaCungCap_Ten, sp.SanPham_NhanHieu, sp.SanPham_XuatXu, sp.SanPham_KichCo, sp.SanPham_SoLuong, sp.SanPham_GiaKhiMua, sp.SanPham_GiaKhiBan, sp.SanPham_GiaUuDai, sp.SanPham_HinhAnh);
                //    dataGridView1.Rows[dataGridView1.Rows.Count - 1].Tag = sp;
                //}
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    row.SetValues(row.Index + 1);
                }
            }
            else
            {
                MessageBox.Show("Thêm thành công");
                dataGridView1.Rows.Clear();
            }
        }

        private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewRow row = dataGridView1.Rows[dataGridView1.SelectedCells[0].RowIndex];

            textBox1.Text = (string)row.Cells[1].Value;
            textBox5.Text = (string)row.Cells[2].Value;
            textBox3.Text = (string)row.Cells[5].Value;
            textBox7.Text = (string)row.Cells[6].Value;
            textBox4.Text = row.Cells[9].Value.ToString();
            textBox8.Text = row.Cells[10].Value.ToString();
            //textBox9.Text = row.Cells[11].Value.ToString();
            if (row.Cells[11].Value != null)
            {
                checkBox1.Checked = true;
                textBox9.Text = row.Cells[11].Value.ToString();
            }
            else
                checkBox1.Checked = false;
            textBox2.Text = (string)row.Cells[7].Value;
            textBox6.Text = row.Cells[8].Value.ToString();
            textBox10.Text = (string)row.Cells[12].Value;

            foreach (LoaiSanPham lsp in comboBox2.Items)
            {
                if(lsp.LoaiSanPham_Ten == (string)row.Cells[3].Value)
                {
                    comboBox2.SelectedItem = lsp;
                }
            }

            foreach (NhaCungCap ncc in comboBox1.Items)
            {
                if (ncc.NhaCungCap_Ten == (string)row.Cells[4].Value)
                {
                    comboBox1.SelectedItem = ncc;
                }
            }

            iIndex = row.Index;
            button5.Enabled = true;
            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
        }

        private void button5_Click_1(object sender, EventArgs e)
        {
            if (textBox1.Text == "" || textBox5.Text == "")
            {
                MessageBox.Show("Không được để trống mã hàng và tên hàng");
                return;
            }

            if (textBox4.Text == "" || textBox8.Text == "")
            {
                MessageBox.Show("Không được để trống giá mua và giá bán");
                return;
            }

            if (textBox6.Text == "")
            {
                MessageBox.Show("Không được để trống số lượng");
                return;
            }

            SanPham sp = new SanPham();
            sp.SanPham_MaHang = textBox1.Text;
            sp.SanPham_Ten = textBox5.Text;

            LoaiSanPham lsp = (LoaiSanPham)comboBox2.SelectedItem;
            sp.MaLoaiSanPham = lsp.MaLoaiSanPham;

            NhaCungCap ncc = (NhaCungCap)comboBox1.SelectedItem;
            sp.MaNhaCungCap = ncc.MaNhaCungCap;

            sp.SanPham_NhanHieu = textBox3.Text;
            sp.SanPham_XuatXu = textBox7.Text;
            if (ws.KiemTraDouble(textBox4.Text))
                sp.SanPham_GiaKhiMua = double.Parse(textBox4.Text);
            else
            {
                MessageBox.Show("Giá mua không hợp lệ");
                return;
            }
            if (ws.KiemTraDouble(textBox8.Text))
                sp.SanPham_GiaKhiBan = double.Parse(textBox8.Text);
            else
            {
                MessageBox.Show("Giá bán không hợp lệ");
                return;
            }

            if (checkBox1.Checked)
            {
                if (ws.KiemTraDouble(textBox9.Text))
                    sp.SanPham_GiaUuDai = double.Parse(textBox9.Text);
                else
                {
                    MessageBox.Show("Giá ưu đãi không hợp lệ");
                    return;
                }
            }

            sp.SanPham_KichCo = textBox2.Text;
            if (ws.KiemTraInt(textBox6.Text))
                sp.SanPham_SoLuong = int.Parse(textBox6.Text);
            else
            {
                MessageBox.Show("Số lượng không hợp lệ");
                return;
            }
            sp.SanPham_HinhAnh = textBox10.Text;

            dataGridView1.Rows[iIndex].SetValues(iIndex + 1, sp.SanPham_MaHang, sp.SanPham_Ten, comboBox2.Text, comboBox1.Text, sp.SanPham_NhanHieu, sp.SanPham_XuatXu, sp.SanPham_KichCo, sp.SanPham_SoLuong, sp.SanPham_GiaKhiMua, sp.SanPham_GiaKhiBan, sp.SanPham_GiaUuDai, sp.SanPham_HinhAnh);
            dataGridView1.Rows[iIndex].Tag = sp;

            textBox1.Clear();
            textBox2.Clear();
            textBox3.Clear();
            textBox4.Clear();
            textBox5.Clear();
            textBox7.Clear();
            textBox8.Clear();
            textBox9.Clear();
            textBox10.Clear();
            textBox1.Focus();

            button5.Enabled = false;
            button1.Enabled = true;
            button2.Enabled = true;
            button3.Enabled = true;
            button4.Enabled = true;
            foreach (DataGridViewColumn column in dataGridView1.Columns)
            {
                column.SortMode = DataGridViewColumnSortMode.Automatic;
            }
        }

        string[] ConvertToStringArray(System.Array values, int columncount)
        {
            // create a new string array
            string[] theArray = new string[columncount];
            // loop through the 2-D System.Array and populate the 1-D String Array
            for (int i = 1; i <= columncount; i++)
            {
                if (values.GetValue(1, i) == null)
                    theArray[i - 1] = "";
                else
                    theArray[i - 1] = (string)values.GetValue(1, i).ToString();
            }
            return theArray;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog open = new OpenFileDialog();
            open.Filter = "XLSX Files|*.xlsx";
            open.Title = "Chọn hình ảnh cho nhân viên";
            open.InitialDirectory = Environment.CurrentDirectory;
            if (open.ShowDialog() == DialogResult.OK)
            {
                // Đoạn code tham khảo ở trang http://forums.congdongcviet.com/showthread.php?t=13061
                // Khởi động chtr Excell

                // Thêm file temp xls
                string workbookPath = open.FileName;

                /*try
                {
                    exBook = exApp.Workbooks.Open(workbookPath,
                        0, false, 5, "", "", false, COMExcel.XlPlatform.xlWindows, "",
                        true, false, 0, true, false, false);

                    // Lấy sheet 1.
                    exSheet = (COMExcel.Worksheet)exBook.Worksheets[1];
                    exSheet.Activate();
                }
                catch (System.Exception ex)
                {
                    exBook.Close(false, false, false);
                    exApp.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(exBook);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(exApp);
                    MessageBox.Show("Mở file bị lỗi");
                    return;
                }*/

                string connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + workbookPath + ";Extended Properties=Excel 12.0;";
                OleDbConnection conn = new OleDbConnection(connstr);
                string strSQL = "SELECT * FROM [Sheet1$]";

                OleDbCommand cmd = new OleDbCommand(strSQL, conn);
                DataSet ds = new DataSet();
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                da.Fill(ds);

                DataTable table = ds.Tables[0];

                int n = 0;
                try
                {
                    double d = (double)table.Rows[0].ItemArray[0];
                    n = Convert.ToInt32(d);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("File xlsx bị lỗi");
                    return;
                }

                for (int i = 0; i < n; ++i)
                {
                    SanPham sp = new SanPham();
                    try
                    {
                        sp.SanPham_MaHang = (string)table.Rows[i].ItemArray[2];
                        sp.SanPham_Ten = (string)table.Rows[i].ItemArray[3];

                        double c = (double)table.Rows[i].ItemArray[4];
                        double q = (double)table.Rows[i].ItemArray[5];
                        sp.MaLoaiSanPham = Convert.ToInt32(c);
                        sp.MaNhaCungCap = Convert.ToInt32(q);

                        if (table.Rows[i].ItemArray[6] != System.DBNull.Value)
                            sp.SanPham_NhanHieu = (string)table.Rows[i].ItemArray[6];
                        else
                            sp.SanPham_NhanHieu = "";
                        if (table.Rows[i].ItemArray[7] != System.DBNull.Value)
                            sp.SanPham_XuatXu = (string)table.Rows[i].ItemArray[7];
                        else
                            sp.SanPham_XuatXu = "";

                        if (table.Rows[i].ItemArray[8] != System.DBNull.Value)
                            sp.SanPham_KichCo = (string)table.Rows[i].ItemArray[8];
                        else
                            sp.SanPham_KichCo = "";

                        double d = (double)table.Rows[i].ItemArray[9];
                        sp.SanPham_SoLuong = Convert.ToInt32(d);

                        sp.SanPham_GiaKhiMua = (double)table.Rows[i].ItemArray[10];
                        sp.SanPham_GiaKhiBan = (double)table.Rows[i].ItemArray[11];
                        if (table.Rows[i].ItemArray[12] != System.DBNull.Value)
                        {
                            sp.SanPham_GiaUuDai = (double)table.Rows[i].ItemArray[12];
                        }
                        else
                            sp.SanPham_GiaUuDai = null;

                        if (table.Rows[i].ItemArray[13] != System.DBNull.Value)
                            sp.SanPham_HinhAnh = (string)table.Rows[i].ItemArray[13];
                        else
                            sp.SanPham_HinhAnh = "";

                        LoaiSanPham lsp = ws.SanPham_LayLoaiSP(sp);
                        NhaCungCap ncc = ws.SanPham_LayNCC(sp);

                        dataGridView1.Rows.Add(dataGridView1.Rows.Count + 1, sp.SanPham_MaHang, sp.SanPham_Ten, lsp.LoaiSanPham_Ten, ncc.NhaCungCap_Ten, sp.SanPham_NhanHieu, sp.SanPham_XuatXu, sp.SanPham_KichCo, sp.SanPham_SoLuong, sp.SanPham_GiaKhiMua, sp.SanPham_GiaKhiBan, sp.SanPham_GiaUuDai, sp.SanPham_HinhAnh);
                        dataGridView1.Rows[dataGridView1.Rows.Count - 1].Tag = sp;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Có lỗi khi xử lý sản phẩm thứ " + (i + 1).ToString());
                        return;
                    }
                }
                MessageBox.Show("Thành công");
            }
        }
    }
}
